package com.rd.sys.service.analysis.event.impl;

import baseproj.common.exception.BaseServiceException;
import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.DateTimeUtils;
import com.rd.sys.common.utils.JacksonMapper;
import com.rd.sys.common.utils.cache.AnalysisCache;
import com.rd.sys.common.utils.client.AnalysisPathUtils;
import com.rd.sys.dto.client.store.EventModel;
import com.rd.sys.dto.client.store.Result;
import com.rd.sys.service.analysis.event.EventService;
import com.rd.sys.service.analysis.result.ResultService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <br/>
 *
 * @author admin
 * @title 》EventServiceImpl
 * @data 2019-12-30 13:22
 * @since 1.0.1
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class EventServiceImpl implements EventService {

    protected static final Logger logger = LoggerFactory.getLogger(EventServiceImpl.class);

    @Autowired
    private ResultService resultService;

    @Override
    public List<EventModel> queryEventList(String userCode, String projectCode, String schemeCode) throws Exception {
        List<EventModel> tempDataList = new ArrayList<EventModel>();
        // 查询所有的结果数据集
        List<Result> rltList = resultService.queryResultList(userCode, projectCode, schemeCode);
        if (!CollectionUtils.isEmpty(rltList)) {
            for (Result rt : rltList) {
                List<EventModel> emList = this.queryEventList(userCode, projectCode, schemeCode, rt.getResultCode());
                tempDataList.addAll(emList);
            }
        }
        return tempDataList;
    }

    @Override
    public List<EventModel> queryEventList(String userCode, String projectCode, String schemeCode, String resultCode) {
        // 没有结果说明没得任何事件，防止空问题
        if (StringUtils.isEmpty(resultCode)) {
            return new ArrayList<EventModel>();
        }
        // 结果集查询数据信息
        try {
            /** 读取方案下所有被试信息 */
            String key = userCode + CommonConstants.AnalysisConstats.CACHE_SPLIT + projectCode
                    + CommonConstants.AnalysisConstats.CACHE_SPLIT + schemeCode
                    + CommonConstants.AnalysisConstats.CACHE_SPLIT + resultCode;
            return AnalysisCache.EventCache.get(key);
        } catch (BaseServiceException be) {
            throw be;
        } catch (Exception ex) {
            logger.error("query result error", ex);
            throw new RuntimeException(ex);
        }
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<EventModel> readResultList(String key) throws Exception {
        List<EventModel> resultList = new LinkedList<EventModel>();

        /** key由usercode、projectcode、schmecode组成 */
        String[] keys = key.split(CommonConstants.AnalysisConstats.CACHE_SPLIT);
        String userCode = keys[0];
        String projectCode = keys[1];
        String schemeCode = keys[2];
        String resultCode = keys[3];

        /** 从被试描述文件中读取出来 */
        File file = new File(AnalysisPathUtils.findEventDataFileName(userCode, projectCode, schemeCode, resultCode));
        if (!file.exists()) {
            file.createNewFile(); // 对文件为空时做个保护
        } else {
            List<String> result = FileUtils.readLines(file, CommonConstants.SysParamConstants.SYS_CHARSET);
            if (!CollectionUtils.isEmpty(result)) {
                for (String rt : result) {
                    EventModel model = (EventModel) JacksonMapper.json2Bean(rt, EventModel.class);

                    // 将时间戳转化成日期
                    if (!StringUtils.isEmpty(model.getEventTime())) {
                        String time = DateTimeUtils.formatDatetimeOfLong(model.getEventTime());
                        model.setEventTimes(DateTimeUtils.formatDatetimeOfLong(model.getEventTime(), DateTimeUtils.millisecondFormat));
                        model.setEventTime(time);
                    }

                    resultList.add(model);
                }
            }
        }
        return resultList;
    }
}
